<?php

namespace App\Services\Java;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
use function GuzzleHttp\Psr7\str;
use Log;

class JavaClient
{
    private Client $client;

    /**
     * 请求初始化
     * FaceClient constructor.
     */
    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => config('services.java.url'),
            'timeout' => 15.0, //秒
            'debug' => false,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Accept-Language' => 'zh-CN,zh;q=0.9,en;q=0.8,sm;q=0.7',
                'Accept-Encoding' => 'gzip',
            ],
        ]);
    }

    public function request(string $method, string $url, $data = [], array $options = [])
    {
        $method = strtoupper($method);
        try {
            $response = $this->client->request($method, $url, $data + $options);

            if ($response->getStatusCode() === 200) {
                $body = $response->getBody();

                $result = json_decode((string)$body, true);

                if (is_array($result)) {
                    throw_on($result['code'] !== '0', $result['message']);
                    return $result['data'] ?? [];
                } else {
                    return null;
                }
            } else {
                throw_e(new Exception('请求失败：' . $url));
            }
        } catch (TransferException $e) {
            if ($e->hasResponse()) {
                Log::error('ExHttp 请求失败：' . str($e->getResponse()));
            }
            throw $e;
        }
        return $response;
    }

    public function __call(string $method, array $params)
    {

    }
}
